package core

import (
	"fmt"
	partner "gitee.com/binny_w/gin-partner"
	"github.com/gin-gonic/gin"
	"time"
)

var Engine *partner.Engine
var ApiGroup *gin.RouterGroup

func engineInit() {
	formatter := func(param gin.LogFormatterParams) string {
		var statusColor, methodColor, resetColor string
		if param.IsOutputColor() {
			statusColor = param.StatusCodeColor()
			methodColor = param.MethodColor()
			resetColor = param.ResetColor()
		}

		if param.Latency > time.Minute {
			param.Latency = param.Latency.Truncate(time.Second)
		}
		region, _ := Ip2region.Search(param.ClientIP)
		return fmt.Sprintf("[GIN] %v |%s %3d %s| %13v | %15s | %s |%s %-7s %s %#v\n%s",
			param.TimeStamp.Format("2006/01/02 - 15:04:05"),
			statusColor, param.StatusCode, resetColor,
			param.Latency,
			param.ClientIP,
			region,
			methodColor, param.Method, resetColor,
			param.Path,
			param.ErrorMessage,
		)
	}
	Engine = partner.NewEngine(Config.GetString("gin.mode"), Config.GetString("gin.log"), formatter)
	Engine.UseMiddlewares(partner.RateLimit(RedisRateLimit, 40, 30*time.Second), auth)
	ApiGroup = Engine.RouterGroup("/api")
}
